/**
 * @name RadioList
 * @author darcrand
 * @desc 单选
 */

import React, { Component } from 'react'
import './styles.scss'

class RadioList extends Component {
    static defaultProps = {
        title: '漫威英雄',
        options: [
            { label: '美国队长', val: '1' },
            { label: '钢铁侠', val: '2' },
            { label: '蜘蛛侠', val: '3' },
            { label: '雷神', val: '4' }
        ],
        onChange: (option, index) => {
            console.log('changed', option, index)
        }
    }

    state = {
        isOpen: true,
        curr: this.props.options[0]
    }

    onTitleClick = () => {
        this.setState(pre => ({ isOpen: !pre.isOpen }))
    }

    onOptionClick = (option, index) => {
        this.setState({ curr: option })
        this.props.onChange(option, index)
    }

    render() {
        const { title, options } = this.props
        const { curr } = this.state
        const { isOpen } = this.state

        return (
            <div classes="container">
                <p classes={isOpen ? 'title-open' : 'title-close'} onClick={this.onTitleClick}>
                    {title}
                </p>
                {isOpen && (
                    <ul classes="list">
                        {options.map((v, i) => (
                            <li
                                key={i}
                                classes={curr && v.val === curr.val ? 'item-checked' : 'item-normal'}
                                onClick={() => this.onOptionClick(v, i)}
                            >
                                {v.label}
                            </li>
                        ))}
                    </ul>
                )}
            </div>
        )
    }
}

export default RadioList
